/*
 * msccallback.c
 *
 *  Created on: 13-02-2012
 *      Author: Mateusz
 */

#include "LPC13xx.h"
#include <cr_section_macros.h>

#include "iap.h"
#include "diskimg.h"

extern uint8_t  user_flash_erased; // from main_bootloader.c

 const uint8_t InquiryStr[] = "SFAR    RibbonControl BL    ";


void MSC_MemoryRead (uint32_t offset, uint8_t dst[], uint32_t length) {

	uint32_t i;
	uint8_t data;
	uint8_t * firmware;
	firmware = (uint8_t *)USER_FLASH_START;


	for ( i = 0; i<length; i++)
	{
		if (offset < BOOT_SECT_SIZE)
		{

	      switch (offset)
		  {
		    case 19:
				data = (uint8_t)(MSC_BlockCount & 0xFF);
				break;
		    case 20:
				data = (uint8_t)((MSC_BlockCount >> 8) & 0xFF);
				break;
			case 510:
				data = 0x55;
				break;
			case 511:
				data = 0xAA;
				break;
			default:
				if ( offset > 0x3E )
				{
				  data = 0x0;
				}
				else
				{
				  data = BootSect[offset];
				}
				break;
		  }

		}
		else if (offset < (BOOT_SECT_SIZE + FAT_SIZE + ROOT_DIR_SIZE))
		     {
				data = Fat_RootDir[offset - BOOT_SECT_SIZE];
			 }
			 else
			 {
				 //data = *(firmware + (offset - (BOOT_SECT_SIZE + FAT_SIZE + ROOT_DIR_SIZE)));
				 data = 0x00;
			 }

	    dst[i] = data;
	    offset++;
	  }

}


void MSC_MemoryWrite (uint32_t offset, uint8_t src[], uint32_t length) {

	uint8_t * firmware;
	firmware = (uint8_t *)USER_FLASH_START;

	uint32_t i;



	if (offset < BOOT_SECT_SIZE)
	{
	  // Can't write boot sector
	}
	else if (offset < (BOOT_SECT_SIZE + FAT_SIZE + ROOT_DIR_SIZE))
		 {
		   for ( i = 0; i<length; i++)
		   {
			   	Fat_RootDir[(offset+i) - BOOT_SECT_SIZE] = src[i];

			 if ( src[i] == 0xe5 )
			 {
				 if ( (offset+i) == BOOT_SECT_SIZE + FAT_SIZE + 32 )
				 {
					// Delete user flash when firmware.bin is erased
					if( user_flash_erased == 0 )
					{
					  erase_user_flash();
					  user_flash_erased = 1;
					}
				 }

			 }
		   }
		 }
		 else
		 {
		   write_flash((unsigned *)(firmware + (offset - (BOOT_SECT_SIZE + FAT_SIZE + ROOT_DIR_SIZE))),(char *)src,length);
		   // [pbBuf casted to signed char pointer as that is what write_flash routine expects]
		 }

}
